/**
 * Created by chenweiwei on 2019/5/23.
 */
/*
 const {Tool: { hideLoading, redirectTo, sensors, showLoading, showToast },Tool, Event, Storage, API, throttle} = global.$util

import {getSubscribeMsgTemplate, checkBindSub, subscribeMsg} from '../../../tools/msgSubscribe'

function nav(subType, success, groupId, isAllXNProd) {
	let txt = '订阅失败'
	if(success){
		txt = '订阅成功'
	}
	showToast(txt)
	setTimeout(() => {
		if (subType === 1) {
			redirectTo(`/pages/group-buying/detail/detail?groupId=${groupId}`)
		} else if (subType === 2) {
			redirectTo(`/pages/order-confirm/pay/pay-result/pay-result?payResult=${true}&isAllNXProd=${isAllXNProd || false}`)
		} else {
			redirectTo(`/pages/order-confirm/pay/pay-result/pay-result?payResult=${true}&isAllNXProd=${isAllXNProd || false}`)
		}
	}, 1000)
}
export default class OrderPayFactory {

    static  timer = null

    static  tryPayTimes = 0

    static page = ''

    static fundsTradingNo = '' // 支付单号

    static payList = {}  // 支付清单

    static payAmount = '0.00'  // 实际支付金额

    static wakeUpWxpay = false
    // 获取验签
    static init(payList,wakeUpWxpay,page,cb=()=>{}){
        this.page = page
        this.payList = payList || {}
        this.wakeUpWxpay = wakeUpWxpay
        // this.checkPay({},cb)
        this.queryPaySign(cb)
    }

    static queryPaySign(cb=()=>{}){

        API.queryPaySign({
            platformOrderNo:this.payList.platformOrderNo || '',
        }).then((res) => {
            this.checkPay(res.data || {},cb)
        }).catch((res) => {
            this.page.data.btnDisabled = false
            console.log(res)
        })
    }

    //检查是否支付了 参数支付数据 当前页面的this 是否唤起微信支付
    static checkPay(paySignResult={},cb=()=>{}){

        API.checkPay({
            bizType: 0,
            payAmount: paySignResult.payAmount || 0,
            outTradeNo: this.payList.platformOrderNo || '',
            tradeDesc: '秀购小程序支付订单',
            modeType: 0,
            signData: paySignResult.paySign || '',
            version: paySignResult.payVersion || '',
            returnUrl: paySignResult.payCallBackUrl || ''
        }).then((res) => {
            let data = res.data || {}
            this.fundsTradingNo = data.fundsTradingNo || ''
            this.payAmount = data.unpaidAmount || '0.00'
            if (data.code == 0 || data.code == 3 || data.code == 2) {
                cb(data)
                if(this.wakeUpWxpay){
                    this.payOrder()
                }
            } else {
                this.showPayTips(data.code)
            }
        }).catch((res) => {
            this.page.data.btnDisabled = false
        })
    }

    // 普通支付流程
    static payOrder() {
        let payType = this.payAmount == '0.00' || this.payAmount == '0.0' ?  0 : 2
        API.wxPay({
            fundsTradingNo: this.fundsTradingNo,
            detail: [
                {
                    payType: payType,
                    payAmount: this.payAmount
                }
            ]
        }).then((res) => {
            let datas = res.data || {}
            if (this.payAmount == 0 || this.payAmount == '0.00' || this.payAmount == '0.0') {
                this.payInfo()
                // this.paySuccess(datas)
            } else {
                let payInfo = datas.detail.filter((item)=> {
                    return item.payType == 2
                })
                this.wxPay(payInfo[0].payResult)
            }
        }).catch((res) => {
            this.page.data.btnDisabled = false
            console.log(res)
        })
    }

    //微信支付
    static wxPay(payList) {
        payList = JSON.parse(payList)
        let that = this
        wx.requestPayment({
            'timeStamp': payList.timeStamp,
            'nonceStr': payList.nonceStr,
            'package': payList.package,
            'signType': payList.signType || 'MD5',
            'paySign': payList.paySign,
            'success': function (res) {
                that.payInfo()
            },
            'fail': function (res) {
                that.showPayTips(2)
            }
        })
    }

    // 查询支付是否成功
    static payInfo(){
        if(!this.tryPayTimes){
            wx.showLoading({
                title: '订单支付中,请勿重复支付',
            })
        }
        API.payInfo({
            fundsTradingNo: this.fundsTradingNo,
            bizType: 0
        }).then((res) => {
            let data = res.data || {}
            if (data.status !== 0) {
                wx.hideLoading()
                this.page.data.btnDisabled = false
            }
            if(this.timer) clearTimeout(this.timer)
            if (data.status === 0) {
                if(this.tryPayTimes<10){
                    this.timer = setTimeout(()=>{
                        this.payInfo()
                        this.tryPayTimes+=1
                    },500)
                } else {
                    this.redirectToMyOrderPage()
                }

            } else if (data.status == 1) {
                this.paySuccess(data)
            }  else {
                this.showPayTips(data.status)
            }
        }).catch((res) => {
            wx.hideLoading()
            this.showPayTips(2)
            console.log(res)
        })
    }

    // 支付失败的一些提示
    static showPayTips(code){
        let msg = {
            0: "订单待支付",
            1: '该订单已支付成功,请勿重拍',
            2: '订单支付失败',
            3: '平台支付成功,需第三方付款',
            5: '该订单已关闭,请重拍',
        }[code]
        Tool.showToast(msg,()=>{
            if (code == 5) {
                Tool.navigationPop()
            } else if (code == 1) {
                this.redirectToMyOrderPage(1)
            } else if (code == 2){
                this.redirectToPayResultPage(false)
            }
        })
    }
    //跳转到我的订单页面
    static redirectToMyOrderPage (query='') {
        // query = this.payList.isAllNXProd? 4:query
        Tool.redirectTo('/pages/my/my-order/my-order?query='+query)
    }

    //跳转到我的订单页面
    static redirectToPayResultPage (result) {
        if(this.page.groupId){
            Tool.redirectTo(`/pages/group-buying/detail/detail?groupId=${this.page.groupId}`)
            return
        }
        Tool.redirectTo(`/pages/order-confirm/pay/pay-result/pay-result?payResult=${result}&isAllNXProd=${this.payList.isAllXNProd || false}&platformOrderNo=${this.payList.platformOrderNo}`)
    }

    // 获取消息模板列表
	static subscribeMsg (datas) {
		// 子类型 subType：0-普通订单，1-拼团开团单，2-拼团参团单
		let {
			productOrderList=[],
			payInfo={},
			subType,
			platformOrderNo: activityCode
		}  = datas
		let attachments = datas.attachments || {}
		const batchNo = attachments.batchNo || ''
		let activityList = (productOrderList[0] || {}).activityList || []
		let groupId = ''
		if(activityList.length){
			const item = activityList[0] || {}
			if(item.activityTag === 101108 && batchNo){
				groupId = batchNo
			}
		}

		let bizCode = 'queue.normal.order.pay'
		if(subType === 1 || subType === 2){
			bizCode = 'queue.group.order.pay'
		}
		let openId = Storage.getWxOpenid() || ''

		return new Promise((resolve, reject) => {
			getSubscribeMsgTemplate(bizCode).then(tempList => {
				// 参团过滤成团消息
				if (subType === 2) {
					tempList = tempList.filter(v => v.sceneType !== 'group_success')
				}

				// 检查上一部获取的模板是否已订阅
				checkBindSub({ bizCode, activityCode, openId, templateIds: tempList.map(v => v.templateId), }).
					then(result => {
						let unbindResult = result.filter(v => !v.subscribeStatus)

						// 填充 sceneType
						unbindResult.forEach(j => j.sceneType = (tempList.find(k => k.templateId === j.templateId).sceneType))

						wx.requestSubscribeMessage({
							tmplIds: unbindResult.map(v => v.templateId),
							success: (res) => {
								const iterations = Object.entries(res) || []
								let acceptResult = unbindResult.filter(v => {
									let flag = false

									for (let [key,value] of iterations) {
										if(v.templateId === key && value === 'accept') {
											flag = true
											break
										}
									}

									return flag
								})
								if (res.errMsg === 'requestSubscribeMessage:ok' && acceptResult.length > 0) {
									subscribeMsg({
										activityCode,
										bizCode,
										openId,
										bindItems: acceptResult.map(v => ({
											sceneType: v.sceneType,
											templateId: v.templateId,
										})),
									}).
										then(() => {
											resolve(true)
											// nav(subType, true, groupId, params.isAllXNProd)
										}).
										catch(() => {
											resolve(false)
											// nav(subType, false, groupId, params.isAllXNProd)
										})
								} else {
									resolve(false)
									// nav(subType, false, groupId, params.isAllXNProd)
								}
							},
							fail: () => {
								resolve(false)
								// nav(subType, false, groupId, params.isAllXNProd)
							},
						})
					})
			}).catch(err => {
				console.error(err)
			})
		})

	}

    // 支付成功以后跳转
    static paySuccess(datas){
		// 消息订阅
		this.subscribeMsg(datas).then(result => {


			if(result) {
				showToast('订阅成功')
			}

			wx.showLoading({
				title: '支付结果查询中....',
			})

			API.getUserJudgeShare({

			}).then((res) => {
				wx.hideLoading()
				let datas = res.data || {}
				if(datas.isShare){
					Tool.redirectTo('/pages/order-confirm/pay/pay-activity/pay-activity?code='+datas.shareCode)
				} else {
					this.redirectToPayResultPage(true)
				}
			}).catch((res) => {
				this.redirectToPayResultPage(true)
				wx.hideLoading()
			})
			Tool.sensors('ViewOrderPaySuccessPage',{})
		}).catch(err =>{
			console.error(err)
		})


    }


}
*/
